<template>
	<view class="container">
		<uni-nav-bar :title="'入库新增'" fixed statusBar :border="false" height="88rpx" left-icon="left" @clickLeft="onClickLeft"></uni-nav-bar>
		<view class="content" :style="{paddingBottom: `calc(${safeAreaBottom}px + 80rpx)`}">
			<uni-forms ref="form" :rules="rules" :model="valiFormData" :label-width="90" validate-trigger="blur">
				<uni-forms-item label="商品名称：" required name="commodityName1">
					<uni-combox v-model="valiFormData.commodityName1" emptyTips="暂无匹配商品" placeholder="输入商品名称进行搜索" :candidates="candidates1" confirm-type="search"
						@input="debouncedSearch1" @select="onSelectChange1" :disable="id !== ''"></uni-combox>
				</uni-forms-item>
				<uni-forms-item label="商品条码：" required name="barCode1">
					<uni-combox v-model="valiFormData.barCode1" emptyTips="暂无匹配商品" placeholder="输入商品条码进行搜索" :candidates="candidates2" confirm-type="search"
						@input="debouncedSearch2" @select="onSelectChange2" :disable="id !== ''"></uni-combox>
				</uni-forms-item>
				<uni-forms-item label="入库数量：" required name="num">
					<uni-easyinput v-model="valiFormData.num" type="number" placeholder="请输入入库数量" adjust-position confirm-type="next" />
				</uni-forms-item>
				<uni-forms-item label="进货价：" required name="buyingPrice">
					<uni-easyinput v-model="valiFormData.buyingPrice" type="number" placeholder="请输入进货价" adjust-position confirm-type="next">
						<template #right>
							<view>元</view>
						</template>
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="零售价：" required name="storePrice">
					<uni-easyinput v-model="valiFormData.storePrice" type="number" placeholder="请输入零售价" adjust-position confirm-type="done">
						<template #right>
							<view>元</view>
						</template>
					</uni-easyinput>
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="bottomFix btn type-1 toLeft" :style="{paddingBottom:safeAreaBottom + 'px'}" @click.stop="toSubmit">
			<text>确 定</text>
		</view>
	</view>
</template>

<script>
	import { debounce } from 'lodash';
	import { reqSelfByNameOrBarCode } from '@/apis/goods.js'
	import { mapGetters } from 'vuex'
	import { nanoid } from 'nanoid';
	export default {
		name: 'ZyDetail',
		data() {
			return {
				candidates1: [],
				candidates2: [],
				goodsList: [],
				id: '',
				valiFormData: {
					id: '',
					commodityName:'',
					barCode:'',
					commodityName1: '',
					barCode1: '',
					num: null,
					buyingPrice: '',
					storePrice: ''
				},
				// 校验规则
				rules: {
					commodityName1: {
						rules: [{
							required: true,
							errorMessage: '请输入商品名称'
						}]
					},
					barCode1: {
						rules: [{
							required: true,
							errorMessage: '商品条码不能为空'
						}]
					},
					num: {
						rules: [{
								required: true,
								errorMessage: '请输入入库数量',
							},
							{
								validateFunction: function(rule, value, data, callback) {
									let reg = /^[1-9]\d*$/
									if (!reg.test(+value)) {
										callback('入库数量只能为正整数')
									}
								}
							}
						],
					},
					buyingPrice: {
						rules: [{
								required: true,
								errorMessage: '请输入进货价',
							},
							{
								format: 'number',
								errorMessage: '进货价格式错误'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									let reg = /^(?!(^0$|0\.0{1,2}$))[0-9]+(\.[0-9]{1,2})?$/
									if (!reg.test(value)) {
										callback('进货价最多两位小数')
									}
								}
							}
						],
					},
					storePrice: {
						rules: [{
								required: true,
								errorMessage: '请输入零售价',
							},
							{
								format: 'number',
								errorMessage: '零售价格式错误'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									let reg = /^(?!(^0$|0\.0{1,2}$))[0-9]+(\.[0-9]{1,2})?$/
									if (!reg.test(value)) {
										callback('零售价最多两位小数')
									}
								}
							}
						],
					}
				},
			}
		},
		computed: {
			...mapGetters('zyRk', ['addGoodsList']),
		},
		onLoad(params) {
			this.id = params?.id;
			if (this.id) {
				const obj = this.addGoodsList.find(item => item.id === this.id);
				this.valiFormData.id = obj.id;
				this.valiFormData.commodityName = obj.commodityName;
				this.valiFormData.commodityName1 = obj.commodityName1;
				this.valiFormData.num = obj.num;
				this.valiFormData.barCode = obj.barCode;
				this.valiFormData.barCode1 = obj.barCode1;
				this.valiFormData.storePrice = obj.storePrice;
				this.valiFormData.buyingPrice = obj.buyingPrice;
			} else {
				this.id = ''
			}
		},
		beforeDestroy() {
			this.debouncedSearch1.clearTimeout;
			this.debouncedSearch2.clearTimeout;
		},
		methods: {
			// 输入框参数，
			inputName(data) {
				this.getGoodsByName({ key: 'commodityName', value: data })
			},
			inputCode(data) {
				this.getGoodsByName({ key: 'barCode', value: data })
			},
			// 查询接口
			async getGoodsByName(params) {
				const { value, key } = params;
				if (value === '') return;
				let reqObj = {};
				if (key === 'commodityName') {
					reqObj = { commodityName: value };
				} else {
					reqObj = { barCode: value };
				}
				let res = await reqSelfByNameOrBarCode(reqObj);
				if (res.code === 200) {
					if(key === 'commodityName') {
						this.candidates1 = res.data.map(item => ({...item,name:item.commodityName}));
					}else {
						this.candidates2 = res.data.map(item => ({...item,name:item.barCode}));;
					}
					// this.candidates = res.data;
					// this.goodsList = res.data;
					// this.candidates = res.data.map(item => item.name)
				}
			},
			debouncedSearch1: debounce(function(data) {
				this.inputName(data);
			}, 500),
			debouncedSearch2: debounce(function(data) {
				this.inputCode(data);
			}, 500),
			onSelectChange1(e) {
				const obj = this.candidates1.find(item => item.id === e);
				this.valiFormData.id = nanoid();
				this.valiFormData.commodityName = obj.commodityName;
				this.valiFormData.commodityName1 = obj.commodityName;
				this.valiFormData.barCode = obj.barCode;
				this.valiFormData.barCode1 = obj.barCode;
				this.valiFormData.storePrice = obj.storePrice;
				this.valiFormData.buyingPrice = obj.buyingPrice;
				obj.name = obj.barCode;
				this.candidates2 = [obj];
			},
			onSelectChange2(e) {
				const obj = this.candidates2.find(item => item.id === e);
				this.valiFormData.id = nanoid();
				this.valiFormData.commodityName = obj.commodityName;
				this.valiFormData.commodityName1 = obj.commodityName;
				this.valiFormData.barCode = obj.barCode;
				this.valiFormData.barCode1 = obj.barCode;
				this.valiFormData.storePrice = obj.storePrice;
				this.valiFormData.buyingPrice = obj.buyingPrice;
				
				obj.name = obj.commodityName;
				this.candidates2 = [obj];
			},
			toSubmit() {
				this.$refs.form.validate().then((suc) => {
					if (this.id) {
						// 修改
						this.valiFormData.num = +this.valiFormData.num;
						if(this.valiFormData.commodityName != this.valiFormData.commodityName1 || this.valiFormData.barCode != this.valiFormData.barCode1){
							uni.utils.toast('请选择有效商品');
							return ;
						}
						this.$store.dispatch('zyRk/editZyGoods', this.valiFormData)
						this.$navBack();
					} else {
						// 新增
						this.valiFormData.num = +this.valiFormData.num;
						if(this.valiFormData.commodityName != this.valiFormData.commodityName1 || this.valiFormData.barCode != this.valiFormData.barCode1){
							uni.utils.toast('请选择有效商品');
							return ;
						}
						this.$store.dispatch('zyRk/addZyGoods', this.valiFormData);
						this.$navBack();
					}
				}).catch((err) => {
					console.log('表单验证失败');
				})
			}
		},
	}
</script>

<style>
	page {
		background: #f7f7f7;
	}
</style>
<style lang="scss" scoped>
	.content {
		padding: 20rpx;
		box-sizing: border-box;

		.list {
			.item {
				padding: 20rpx 24rpx;
				background-color: #fff;
				border-radius: 8rpx;
				margin-bottom: 20rpx;

				&:nth-last-child(1) {
					margin-bottom: 0;
				}

				.line {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: $uni-font-size-small;
					color: #333;
					// margin-bottom: 10rpx;
					height: 50rpx;

					.left,
					.right {
						width: 50%;
					}

					.left {
						text-align: left;
					}

					.right {
						text-align: right;
					}
				}

				.btn {
					width: 120rpx !important;
					position: absolute;
					font-size: $uni-font-size-small;
					text-align: center;
					border-radius: 5rpx;
					height: 60rpx;
					box-sizing: border-box;
					line-height: 60rpx;
					bottom: 20rpx;
					right: 24rpx;
				}
			}
		}
	}

	.bottomFix {
		position: fixed;
		width: 100%;
		height: 80rpx;
		bottom: 0;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: $uni-font-size-base;
	}
</style>